import useInitState from '@/hooks/useInitialState'
import { logout } from '@/store/actions/login'
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/store/actions/profile'
// import { RootState } from '@/types/store'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import dayjs from 'dayjs'
import React, { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import EditInput from './EditInput'
import EditList from './EditList'
// import { useEffect } from 'react'
// import { useDispatch, useSelector } from 'react-redux'

import styles from './index.module.scss'

const Item = List.Item

type InputState = {
  type: '' | 'name' | 'intro'
  visible : boolean
}
type ListState = { visible: boolean, type: '' | 'gender' | 'photo'}

const ProfileEdit = () => {
  const { userProfile } = useInitState(getUserProfile, 'profile')
  const [showInput, setShowInput] = useState <InputState>({ type: '', visible: false })
  const [showList, setShowList] = useState <ListState>({ type: '', visible: false })
  const [showBirthday, setShowBirthday] = useState(false)
  const fileRef = useRef<HTMLInputElement>(null)
  const dispatch = useDispatch()
  const history = useHistory()
  // 按钮禁用状态
  const [flag, setFlag] = useState(true)

  // 隐藏
  const hideInput = () => {
    setShowInput({ type: '', visible: false })
  }
  const hideList = () => {
    setShowList({ type: '', visible: false })
  }
  // 拿到提交的数据
  const onUpdate = async (tpye:string, val:string) => {
    if (tpye === 'photo') {
      fileRef.current!.click()
      return
    }
    await dispatch(updateUserProfile(tpye, val))
    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    hideInput()
  }
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    if (!file) return
    const photoData = new FormData()
    photoData.append('photo', file)

    await dispatch(updateUserPhoto(photoData))
    hideList()
  }
  // 修改生日
  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')
    onUpdate('birthday', birthday)
    setShowBirthday(false)
  }

  // 退出
  const onLogout = () => {
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            }
          },
          {
            key: 'confirm',
            text: '退出',
            onClick: () => {
              dispatch(logout())
              history.replace('/login')
              Toast.show({ content: '退出成功' })
            },
            style: {
              color: 'var(--adm-color-weak)'
            }
          }
        ]
      ]
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
        >
          个人信息
        </NavBar>
        <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              onClick={() => { setShowList({ type: 'photo', visible: true }) }}
              arrow
            >
              头像
            </Item>
            <Item arrow extra={userProfile.name} onClick={flag ? () => { setShowInput({ type: 'name', visible: true }); setFlag(false) } : () => {} }>
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span
                  className={classNames('intro', userProfile.intro && 'normal')}
                >
                  {userProfile.intro || '未填写'}
                </span>
              }
              onClick={flag ? () => { setShowInput({ type: 'intro', visible: true }); setFlag(false) } : () => {}}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow extra={!userProfile.gender ? '男' : '女'} onClick={() => { setShowList({ type: 'gender', visible: true }) }}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={() => { setShowBirthday(true) }}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>退出登录</Button>
        </div>
      </div>
      {/* 编辑内容-简介-昵称 */}
      <Popup visible={showInput.visible} position="right" destroyOnClose afterClose={() => { setFlag(true) }}>
            <EditInput hideInput={hideInput} type={showInput.type} onFinish={onUpdate} />
        </Popup>
      {/* 编辑内容-头像-性别 */}
      <Popup onMaskClick={hideList} visible={showList.visible} position="bottom" destroyOnClose >
            <EditList hideList={hideList} type={showList.type} onUpdate={onUpdate} />
        </Popup>
        <DatePicker
      visible={showBirthday}
      value={new Date(userProfile.birthday)}
      onCancel={() => { setShowBirthday(false) }}
      title="选择年月日"
      min={new Date(1900, 0, 1, 0, 0, 0)}
      max={new Date()}
      onConfirm={(value: Date) => { onUpdateBirthday(value) }}
    />
    </div>
  )
}

export default ProfileEdit
